package com.demo.jvm.chapter2.heap;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.List;

public class RuntimeConstantPoolOOM {

  public static void main(String[] args) {
    // 使用Set保持着常量池引用，避免Full GC回收常量池行为
    List<String> set = new ArrayList<>();
    // 在short范围内足以让6MB的PermSize产生OOM了
    short i = 0;
    while (true) {
      MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

      MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
      MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();

      System.out.println("堆的初始值：" + heapMemoryUsage.getInit() / 1024 / 1024 + "MB");
      System.out.println("堆的当前使用值：" + heapMemoryUsage.getUsed() / 1024 / 1024 + "MB");
      System.out.println("堆的已提交值：" + heapMemoryUsage.getCommitted() / 1024 / 1024 + "MB");
      System.out.println("堆的最大值：" + heapMemoryUsage.getMax() / 1024 / 1024 + "MB");
      set.add(String.valueOf(i++).intern());
      try {
        Thread.sleep(10);
        System.out.println(set.size());
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}